package com.community.backend.service.impl;

import com.alibaba.fastjson.JSON;
import com.community.backend.mapper.ShareFeeMapper;
import com.community.backend.pojo.Fee;
import com.community.backend.pojo.ShareFee;
import com.community.backend.pojo.vo.ShareFeeQueryVO;
import com.community.backend.pojo.dto.ShareFeeQueryDTO;
import com.community.backend.service.ShareFeeService;
import com.community.backend.utils.PageResult;
import com.community.backend.utils.RedisUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class ShareFeeServiceImpl implements ShareFeeService {
    private final ShareFeeMapper shareFeeMapper;
    public ShareFeeServiceImpl(ShareFeeMapper shareFeeMapper) {
        this.shareFeeMapper = shareFeeMapper;
    }
    @Override
    public PageResult pageQuery(ShareFeeQueryDTO shareFeeQueryDTO) {
        PageHelper.startPage(shareFeeQueryDTO.getCurrentPage(),shareFeeQueryDTO.getPageSize());
        Page<ShareFeeQueryVO> page = shareFeeMapper.pageQuery(shareFeeQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void save(ShareFee shareFee) {
        shareFee.setId(UUID.randomUUID().toString());
        shareFee.setStatus("未缴");
        shareFee.setIsDelete("未删除");
        shareFeeMapper.insert(shareFee);
    }

    @Override
    public void update(ShareFee shareFee) {
        shareFeeMapper.update(shareFee);
    }

    @Override
    public void deleteById(String id) {
        ShareFee shareFee = new ShareFee();
        shareFee.setId(id);
        shareFeeMapper.updateById(shareFee);
    }

    @Override
    public ShareFee shareFeeDetail(String id) {
        ShareFee shareFee = shareFeeMapper.selectById(id);
        return shareFee;
    }

    @Override
    public void selectById(String id) {
        ShareFee shareFee = shareFeeMapper.selectById(id);
        String userId = String.valueOf(shareFee.getUserId());
        System.out.println("shareFee"+shareFee);
        Map<String,Object> map = new HashMap<>();
        map.put("sid",userId);
        map.put("message", "费用类型：" + shareFee.getProject()); // 桌面通知 body
        map.put("feeId", shareFee.getId());            // 扩展字段，前端可跳转详情
        map.put("status", shareFee.getStatus());       // 已缴费/未缴费
        map.put("amount", shareFee.getTotalPrice());   // 金额
        String json = JSON.toJSONString(Map.of(
                "sid", userId,
                "message", "您有新的" + shareFee.getProject() + "账单,账单号："+shareFee.getId() +"金额：" + shareFee.getTotalPrice() + "元",
                "feeId", shareFee.getId()));
        String key = "offline:" + userId;          // 不再拼 feeId
        System.out.println("key:"+key);
        System.out.println("json:"+json);
        RedisUtils.redis().opsForList().rightPush(key, json);
    }
}
